package com.codeplatform.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 */
@Slf4j
@Component
public class JwtUtil {
    
    /**
     * JWT密钥
     */
    @Value("${jwt.secret:mySecretKey123456789012345678901234567890}")
    private String secret;
    
    /**
     * JWT过期时间（毫秒）- 默认24小时
     */
    @Value("${jwt.expiration:86400000}")
    private Long expiration;
    
    /**
     * 刷新令牌过期时间（毫秒）- 默认7天
     */
    @Value("${jwt.refresh-expiration:604800000}")
    private Long refreshExpiration;
    
    /**
     * JWT发行者
     */
    @Value("${jwt.issuer:code-platform}")
    private String issuer;
    
    /**
     * 获取密钥
     */
    private SecretKey getSigningKey() {
        return Keys.hmacShaKeyFor(secret.getBytes());
    }
    
    /**
     * 生成访问令牌
     */
    public String generateAccessToken(Long userId, String username, String role) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);
        claims.put("role", role);
        claims.put("type", "access");
        
        return createToken(claims, username, expiration);
    }
    
    /**
     * 生成刷新令牌
     */
    public String generateRefreshToken(Long userId, String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);
        claims.put("type", "refresh");
        
        return createToken(claims, username, refreshExpiration);
    }
    
    /**
     * 创建令牌
     */
    private String createToken(Map<String, Object> claims, String subject, Long expiration) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration);
        
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuer(issuer)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(getSigningKey(), SignatureAlgorithm.HS512)
                .compact();
    }
    
    /**
     * 从令牌中获取用户名
     */
    public String getUsernameFromToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            return claims.getSubject();
        } catch (Exception e) {
            log.error("获取用户名失败", e);
            return null;
        }
    }
    
    /**
     * 从令牌中获取用户ID
     */
    public Long getUserIdFromToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Object userId = claims.get("userId");
            if (userId instanceof Integer) {
                return ((Integer) userId).longValue();
            } else if (userId instanceof Long) {
                return (Long) userId;
            }
            return null;
        } catch (Exception e) {
            log.error("获取用户ID失败", e);
            return null;
        }
    }
    
    /**
     * 从令牌中获取用户角色
     */
    public String getRoleFromToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            return (String) claims.get("role");
        } catch (Exception e) {
            log.error("获取用户角色失败", e);
            return null;
        }
    }
    
    /**
     * 从令牌中获取令牌类型
     */
    public String getTokenTypeFromToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            return (String) claims.get("type");
        } catch (Exception e) {
            log.error("获取令牌类型失败", e);
            return null;
        }
    }
    
    /**
     * 从令牌中获取过期时间
     */
    public Date getExpirationDateFromToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            return claims.getExpiration();
        } catch (Exception e) {
            log.error("获取过期时间失败", e);
            return null;
        }
    }
    
    /**
     * 从令牌中获取Claims
     */
    private Claims getClaimsFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
    
    /**
     * 验证令牌是否过期
     */
    public Boolean isTokenExpired(String token) {
        try {
            Date expiration = getExpirationDateFromToken(token);
            return expiration != null && expiration.before(new Date());
        } catch (Exception e) {
            log.error("检查令牌过期状态失败", e);
            return true;
        }
    }
    
    /**
     * 验证令牌
     */
    public Boolean validateToken(String token, String username) {
        try {
            String tokenUsername = getUsernameFromToken(token);
            return (username.equals(tokenUsername) && !isTokenExpired(token));
        } catch (Exception e) {
            log.error("验证令牌失败", e);
            return false;
        }
    }
    
    /**
     * 验证访问令牌
     */
    public Boolean validateAccessToken(String token) {
        try {
            String tokenType = getTokenTypeFromToken(token);
            return "access".equals(tokenType) && !isTokenExpired(token);
        } catch (Exception e) {
            log.error("验证访问令牌失败", e);
            return false;
        }
    }
    
    /**
     * 验证刷新令牌
     */
    public Boolean validateRefreshToken(String token) {
        try {
            String tokenType = getTokenTypeFromToken(token);
            return "refresh".equals(tokenType) && !isTokenExpired(token);
        } catch (Exception e) {
            log.error("验证刷新令牌失败", e);
            return false;
        }
    }
    
    /**
     * 刷新访问令牌
     */
    public String refreshAccessToken(String refreshToken) {
        try {
            if (!validateRefreshToken(refreshToken)) {
                return null;
            }
            
            Claims claims = getClaimsFromToken(refreshToken);
            Long userId = getUserIdFromToken(refreshToken);
            String username = claims.getSubject();
            
            // 这里需要从数据库获取最新的用户角色
            // 为了简化，暂时使用默认角色
            String role = "user";
            
            return generateAccessToken(userId, username, role);
        } catch (Exception e) {
            log.error("刷新访问令牌失败", e);
            return null;
        }
    }
    
    /**
     * 获取令牌剩余有效时间（秒）
     */
    public Long getTokenRemainingTime(String token) {
        try {
            Date expiration = getExpirationDateFromToken(token);
            if (expiration == null) {
                return 0L;
            }
            
            long remaining = expiration.getTime() - System.currentTimeMillis();
            return Math.max(0L, remaining / 1000);
        } catch (Exception e) {
            log.error("获取令牌剩余时间失败", e);
            return 0L;
        }
    }
    
    /**
     * 解析令牌（不验证签名，用于获取过期令牌的信息）
     */
    public Claims parseTokenWithoutValidation(String token) {
        try {
            String[] chunks = token.split("\\.");
            if (chunks.length != 3) {
                return null;
            }
            
            // 解析payload部分
            String payload = chunks[1];
            byte[] decodedBytes = java.util.Base64.getUrlDecoder().decode(payload);
            String decodedPayload = new String(decodedBytes);
            
            // 这里简化处理，实际应该使用JSON解析
            return null;
        } catch (Exception e) {
            log.error("解析令牌失败", e);
            return null;
        }
    }
    
    /**
     * 生成令牌对（访问令牌和刷新令牌）
     */
    public Map<String, String> generateTokenPair(Long userId, String username, String role) {
        Map<String, String> tokens = new HashMap<>();
        tokens.put("accessToken", generateAccessToken(userId, username, role));
        tokens.put("refreshToken", generateRefreshToken(userId, username));
        return tokens;
    }
}